<!--海外出库-拣货任务-->
<template>
  <div class="page-container">
    <page_breadcrumb :getKeyMethod="init_table_model" @change="change_table_model" pageOption />

    <ex_super_table_page v-bind="option" ref="SuperTablePage" :cell-class-name="cellClassMethod">

    </ex_super_table_page>


    <!-- <detail_standard_pickingTask ref="detail_standard_pickingTask" /> -->
    <standard_pick_down ref="standard_pick_down" @submitSuccess="reload()" />
    <taskAssign ref="PickingTaskAssign" :title="$tt('label_pick_task_assign')" @afterSubmit="afterSubmitPickingTask"
      multiple :intoTableOption="[
      { key: 'pickNo', label: 'label_pick_code' },
      { key: 'waveNo', label: 'label_wave_code' },
    ]" />

    <report_anomaly ref="report_anomaly" :orderTypeList="['PICKING']" system="WMS" @afterSubmitSuccess="reload()" />
    <ex_super_dialog_form ref="reportDialog" v-bind="report_dialog"
      @afterSubmitSuccess="$refs['SuperTablePage'].reload()">
      <template v-slot:dialog_button_footer>
        <el-button type="primary" @click="downloadReport">{{ $tt('label_download') }}</el-button>
        <el-button type="primary" @click="browserPrintReport">
          {{ $tt('label_browser_print') }}
        </el-button>
      </template>
    </ex_super_dialog_form>
  </div>
</template>
<script>

import taskAssign from '@/component/wms/taskAssign.vue';

// import detail_standard_pickingTask from './dialog/detail_standard_pickingTask.vue';
import standard_pick_down from './dialog/standard_pick_down.vue';

import report_anomaly from '@/component/dialog/report_anomaly.vue'

import superTablePageFunction from '@/mixin/super-table-page-function';
import page_table_model_manage from '@/mixin/page_table_model_manage';
import emitOnFunction from '@/mixin/emit-on-function';
let emitKey = 'standard>picking_task_list'
export default {
  title: "title_standard_picking_task",
  mixins: [superTablePageFunction, emitOnFunction(emitKey), page_table_model_manage],
  components: { taskAssign, standard_pick_down, report_anomaly },
  data() {
    return {
      option: {
        search: {
          default: { pickDateType: "ALL" },
          resetFieldFun: (def, org) => {
            def.pickDateType = org.pickDateType;
            def.startHour = org.startHour;
            def.endHour = org.endHour;
            return def
          },
          model: [
            {
              key: 'pickDateType',
              label: 'label_waiting_time',
              itemClass: "w_fill",
              render: (h, { data }) => {
                const list = [
                  { label: this.$t('label_within_hours', ['72']), code: 'null,72' },
                  { label: this.$t('label_n_hours', ['72-96']), code: '72,96' },
                  { label: this.$t('label_n_hours', ['96-120']), code: '96,120' },
                  { label: this.$t('label_over_hours', ['120']), code: '120' }
                ].map(it => (
                  <el-radio-button key={it.code} label={it.code}>
                    {it.label}
                  </el-radio-button>
                ))
                return <el-radio-group
                  value={data.pickDateType}
                  onInput={e => {
                    let time = e.split(',')
                    this.$set(data, 'startHour', e === 'ALL' ? null : time[0])
                    this.$set(data, 'endHour', time[1])
                    this.$set(data, 'pickDateType', e)
                    this.$refs.SuperTablePage.loadDataForSearch()
                  }}>
                  <el-radio-button key="ALL" label="ALL">
                    {this.$tt("label_all")}
                  </el-radio-button>
                  {list}
                </el-radio-group>
              }
            },
            { label: "label_wave_code", key: "waveNo", },
            { label: "label_pick_code", key: "pickNo", },
            { label: "label_pick_status", key: "status", type: 'select', enum: 'PickTaskStatusEnum' },
            { key: 'bizType', label: 'label_business_type', type: 'select', enum: 'BizTypeEnum', },
            { key: 'outType', label: 'label_outbound_type', type: 'select', enum: 'OutboundOrderTypeEnum', },
            { key: 'supplierNames', label: 'label_carrier' },
            { label: "label_is_short_pick", key: "shortPicking", type: 'select', enum: 'YesOrNoEnum' },



            { label: "label_pick_user", key: "pickPerson", fold: true, },



            { label: "label_sku", key: "skuId", type: "sku_selec_input", fold: true, },

            { label: 'label_ec_platform', key: 'ecPlatformName', type: 'select', enum: 'OmsOutboundOrderEcPlatformEnum', fold: true, },
            {
              label: "label_create_time", key: "gmtCreateForm", type: 'date-picker', attrs: { type: 'datetime' },
              render: (h, { data, item }) => {
                const limitKey = 'gmtCreateTo'; const limitValue = data[limitKey]; const value = data[item.key];
                return (<ex_super_input value={value} onInput={e => this.$set(data, item.key, e)} type="date-picker" placeholder="label_start_time"
                  attrs={{ type: 'datetime' }} pickerOptions={{ disabledDate: date => { return limitValue ? (limitValue < date.getTime()) : false } }}
                />)
              }
            },
            {
              label: "~", key: "gmtCreateTo", type: 'date-picker', attrs: { type: 'datetime' },
              render: (h, { data, item }) => {
                const limitKey = 'gmtCreateForm'; const limitValue = data[limitKey]; const value = data[item.key];
                return (<ex_super_input value={value} onInput={e => this.$set(data, item.key, e)} type="date-picker" placeholder="label_end_time"
                  attrs={{ type: 'datetime', 'default-time': '23:59:59' }} pickerOptions={{ disabledDate: date => { return limitValue ? (limitValue > date.getTime()) : false } }}
                />)
              }
            },
            { label: 'label_is_overtime', key: 'isTimeOut', type: 'select', enum: 'YesOrNoEnum', fold: true, },





          ],
        },
        actionExtra: [
          {
            label: 'label_build_pick_report', attrs: { type: "primary" }, auth: 'wms_overseas_outbound_pick_build_report', click: () => {
              this.$refs.reportDialog.showNew({})
            }
          },
          { label: 'label_task_assign', auth: 'wms_overseas_outbound_pick_task_assign', attrs: { type: 'primary' }, click: this.clickPickingTask },
        ],
        table: {
          url: "/wms-api/outbound/OutboundPickingTaskRpc/selectListPage.json",
          model: this.init_table_model()
        },
      },
      report_dialog: {
        customClass: 'dialog_default',
        noSubmit: true,
        form: {
          default: {},
          formDataHandle: (data) => {
            const out = {}
            if (data.daterange && data.daterange.length >= 2) {
              out.startTime = data.daterange[0]
              out.endTime = data.daterange[1]
            }
            return out
          },
          model: [
            {
              label: "label_time_range", key: "daterange",
              render: (h, { data, item }) => {
                const value = data[item.key]
                const attrs = {
                  type: 'datetimerange',
                  'picker-options': {
                    shortcuts: this.$date_range_shortcuts(),
                  },
                }
                return (<ex_super_input value={value} type="date-picker" onInput={e => this.$set(data, item.key, e)}
                  attrs={attrs}
                />)
              }
            },
          ],
          rules: {
            'daterange': { required: true, type: "array", message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
          },
        }
      },
    };
  },
  methods: {
    option_table_model() {
      return [
        { type: 'selection', clickToggle: true },
        { key: 'pickNo', label: 'label_pick_code', 'min-width': 180, },
        { key: 'waveNo', label: 'label_wave_code', 'min-width': 160, },
        { key: 'status', label: 'label_pick_status', 'width': 100, formatter: (r, c, v, i) => this.$enumShow(v, "PickTaskStatusEunm") },
        { key: 'bizType', label: 'label_business_type', 'width': 120, formatter: (r, c, v) => this.$enumShow(v, "BizTypeEnum") },

        {
          key: "areaCodes", label: 'label_hit_area', 'width': 130,
          render: (h, { row }) => {
            const list = row.areaCodes ? (row.areaCodes.split(",").map(it => (<div>{it}</div>))) : null
            return (<div>
              {list}
            </div>)
          }
        },
        { key: 'warehouseCode', label: 'label_outbound_warehouse', 'min-width': 100, 'show-overflow-tooltip': true, },
        {
          key: "supplierNames", label: 'label_pms_supply', 'width': 130,
          render: (h, { row }) => {
            const list = row.supplierNames ? row.supplierNames.split(",").map(it => (<div>{it}</div>)) : null
            return (<div>
              {list}
            </div>)
          }
        },
        {
          key: 'isTimeOut', label: 'label_is_overtime', 'width': 100,
          render: (h, { row, column }) => this.$renderText(h, row[column.property], { enum: "YesOrNoEnum", reverse: true }),
        },
        {
          key: 'shortPicking', label: 'label_is_short_pick', 'width': 100,
          render: (h, { row, column }) => this.$renderText(h, row[column.property], { enum: "YesOrNoEnum", reverse: true }),
        },
        { key: 'waitTime', label: 'label_waiting_time', 'width': 100, },
        { key: 'outStoreType', label: 'label_outbound_type', 'width': 100, formatter: (r, c, v, i) => this.$enumShow(v, "OutboundOrderTypeEnum") },
        { key: 'skuCategoryCount', label: 'label_sku_categ_count', 'width': 100, },
        { key: 'skuTotalPiece', label: 'label_sku_total_count', 'width': 100, },
        {
          key: 'ecPlatformName', label: 'label_ec_platform', 'width': 110, formatter: (r, c, v, i) => {
            if (v) {
              let list = []
              v.split(',').forEach(item => {
                list.push(this.$enumShow(item, "OmsOutboundOrderEcPlatformEnum"))
              })
              return list.join(',')
            } else {
              return ''
            }
          }
        },
        {
          key: 'orderStructureList', label: 'label_order_pick_type', 'width': 100, formatter: (r, c, v, i) => {
            if (v) {
              let list = []
              v.split(',').forEach(item => {
                list.push(this.$enumShow(item, "OutboundOrderStructureEnum"))
              })
              return list.join(',')
            } else {
              return ''
            }
          }
        },
        {
          key: "assignPersonPieceInfo", label: 'label_assign_info', 'width': 130,
          render: (h, { row }) => {
            let list = []
            try {
              list = JSON.parse(row.assignPersonPieceInfo)
            } catch (e) { }
            return (<div>
              {list.map(it => (<div>{it.personName}(<span class="bold color_success">{it.orderCount}</span>)</div>))}
            </div>)
          }
        },
        { key: 'gmtCreate', label: 'label_create_time', 'width': 130, formatter: (r, c, v, i) => this.$dateFormat(v) },
        {
          type: 'operate', width: 140, fixed: 'right', operate: [

            {
              type: 'more',
              items: [
                { label: 'label_view_detail', click: (row) => this.clickDetail(row) },
                { label: 'label_pick_order', disabled: (row) => ['COMPLETED'].includes(row.status), click: (row) => this.pdf_picking_task(row) },

                {
                  label: 'title_pick_down', auth: 'wms_overseas_outbound_pick_down',
                  disabled: (row) => row.status == 'COMPLETED',
                  click: (row) => this.clickPicking(row)
                },
                {
                  label: 'title_pick_finish', auth: 'wms_overseas_outbound_pick_finish',
                  disabled: (row) => row.status != 'UNDERWAY_PICKING' || row.outType == "DESTROY_OUTBOUND",
                  click: (row) => this.confirmPickTask(row)
                },
                {
                  label: 'label_replenish_pick', auth: 'wms_overseas_replenish_pick',
                  disabled: (row) => row.shortPicking != 'Y' || row.status != 'COMPLETED',
                  click: (row) => this.replenishPickTask(row)
                },
                { label: 'label_report_exception', click: (row) => this.reportAnomaly(row) },
              ]
            }
          ]
        }
      ]
    },
    cellClassMethod({ row, column, rowIndex, columnIndex }) {
      if (column.property == 'status') {
        if (row.status == 'COMPLETED') {
          return 'color_success'
        } else if (row.status == 'UNDERWAY_PICKING') {
          return 'color_primary'
        }
      }
      return ""
    },
    reportAnomaly(row) {
      this['$refs']['report_anomaly'].showNew({
        formDisabled: true,
        // submitUrl: '/wms-api/outbound/OutboundPickingTaskRecordDetailRpc/saveAnomaly.json',
        detailUrl: '/wms-api/outbound/OutboundPickingTaskRecordDetailRpc/getOrderInfo.json',
        params: { taskId: row.id },
        detailDataHandle: (data) => {
          return {
            customerId: data.customerId,
            customerCode: data.customerCode,
            customerName: data.customerName,
            orderType: 'OUTBOUND',
            orderNo: data.outOrderNo,
            businessId: row.id
          }
        },

      })

    },
    clickPicking(row) {
      this.$refs['standard_pick_down'].show({ data: { id: row.id } })
    },
    clickDetail(row) {

      // let title = `${this.$tt('label_pick_code')}:${row.pickNo}`
      // this.$refs['detail_standard_pickingTask'].show({ params: { id: row.id }, title })

      this.$router.push({ path: '/page/wms/overseas/outbound/picking_task_detail', query: { id: row.id, } })

    },
    clickPickingTask(e) {
      let _list = this.getSelection();
      if (_list.length == 0) {
        return this.$message.error(this.$tt('tip_please_select_order'))
      }
      if (!this.$loginUser.currentWarehouseId) {
        this.$message.error(this.$tt('tip_please_select_operate_warehouse_first'))
        return
      }

      if (_list.some(it => !['WAIT_ASSIGNED', 'WAIT_PICKING'].some(e => e == it.status))) {
        let checkNoList = []
        _list.forEach(it => {
          if (!['WAIT_ASSIGNED', 'WAIT_PICKING'].some(e => e == it.status)) checkNoList.push(it)
        })
        this.$msgbox_table({
          note: this.$tt('tip_part_order_status_error_no_operate'),
          tableProp: {
            data: checkNoList,
            'max-height': 500,
            model: [
              { key: 'pickNo', label: 'label_pick_code', 'min-width': 140, },
            ]
          }
        }, { title: this.$tt('label_pick_task_assign'), type: 'warning' })
        return
      }
      this.$refs['PickingTaskAssign'].show(this.$loginUser.currentWarehouseId, _list)
    },
    afterSubmitPickingTask({ select, list }) {


      this.$ajax({
        url: "/wms-api/outbound/OutboundPickingTaskRpc/updatePickPerson.json",
        method: 'post', type: 'json',
        data: {
          pickPersons: select.map(it => it.userName),
          taskIds: list.map(it => it.id),
        },
        success: (res) => {
          this.$message.success(this.$tt('tip_submit_success'))
          this.reload()
          this.$refs['PickingTaskAssign'].hide()
        }
      })
    },
    confirmPickTask(row) {
      this.$prompt(this.$tt('tip_please_input_reason'), this.$tt('label_tip'), {
        confirmButtonText: this.$tt('label_confirm'),
        cancelButtonText: this.$tt('label_cancel'),
      }).then(({ value }) => {
        this.$ajax({
          url: "/wms-api/outbound/OutboundPickingTaskRpc/confirmPickTask.json",
          method: 'post', loading: true,
          data: {
            reason: value,
            taskId: row.id,
          },
          success: (res) => {
            this.$message.success(this.$tt('tip_submit_success'))
            this.reload()
          }
        })
      }).catch(() => {
      });

    },
    replenishPickTask(row) {
      this.$confirm(this.$tt('tip_confirm_is_replenish_pick'), this.$tt('label_tip'), {
        type: 'warning'
      }).then(({ value }) => {
        this.$ajax({
          url: "/wms-api/outbound/OutboundPickingTaskRpc/resetPickTask.json",
          method: 'post', loading: true,
          data: {
            taskId: row.id,
          },
          success: (res) => {
            this.$message.success(this.$tt('tip_submit_success'))
            this.reload()
          }
        })
      }).catch(() => {
      });

    },
    pdf_picking_task(row) {
      if (this.$clickFast()) return
      this.$downloadFile({
        loading: true,
        window: true,
        url: '/wms-api/outbound/OutboundPickingTaskRpc/printPdf.json',
        data: {
          taskId: row.id,
        },
      })
    },
    downloadReport(row) {
      this.$refs.reportDialog.validate((valid) => {
        if (valid) {
          this.$downloadFile({
            url: '/wms-api/outbound/OutboundPickingTaskRpc/printPickReport.json',
            data: this.$refs.reportDialog.getFormData(),
            window: true,
          })
        } else {
          this.$message.error(this.$tt("form_validate_error"));
          return false;
        }
      });
    },
    browserPrintReport(row) {
      this.$refs.reportDialog.validate((valid) => {
        if (valid) {
          const url = '/wms-api/outbound/OutboundPickingTaskRpc/printPickReport.json' + `?` + this.$qs.stringify(this.$refs.reportDialog.getFormData());
          printJS({ printable: url, type: "pdf", showModal: true });
        } else {
          this.$message.error(this.$tt("form_validate_error"));
          return false;
        }
      });
    },
  }
};

</script>
<style></style>
